package com.supersit.GZFDA.receiver;

//import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.util.Log;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.supersit.GZFDA.api.APIConstants;
import com.supersit.GZFDA.db.GZFDASqliteDBHelper;
import com.supersit.GZFDA.entity.UnUpLoad;
import com.supersit.GZFDA.util.FileUtils;

/**
 * 后台自动上传广播
 */
public class NetworkConnection extends BroadcastReceiver {
	private Context context;
	private boolean flag = false;
	private List<UnUpLoad> list = new ArrayList<UnUpLoad>();
	private GZFDASqliteDBHelper dbHelper;
	private int count;

	@Override
	public void onReceive(Context context, Intent arg1) {
		this.context = context;
		State wifiState = null;
		State mobileState = null;
		dbHelper = new GZFDASqliteDBHelper(context);
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
		mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
				.getState();
		if (mobileState != null && State.CONNECTED == mobileState
				|| wifiState != null && State.CONNECTED == wifiState) {
			Toast.makeText(context, "网络已连接！！", Toast.LENGTH_SHORT).show();
			if (flag == false)
				setData();
			// 手机网络连接成功
		} else if (wifiState != null && mobileState != null
				&& State.CONNECTED != wifiState
				&& State.CONNECTED != mobileState) {
			Toast.makeText(context, "没有网络！", Toast.LENGTH_SHORT).show();
			// 手机没有任何的网络
		}
	}

	public void setData() {
		flag = true;
		UnUpLoad unUpLoad = new UnUpLoad();
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from unupload", null);
		while (cursor.moveToNext()) {
			unUpLoad.setBZ(cursor.getString(cursor.getColumnIndex("by")));
			unUpLoad.setQYMC(cursor.getString(cursor
					.getColumnIndex("business_name")));
			unUpLoad.setCJSJ(cursor.getString(cursor
					.getColumnIndex("uploaddate")));
			unUpLoad.setCJR(cursor.getString(cursor.getColumnIndex("upuser")));
			unUpLoad.setX(cursor.getString(cursor.getColumnIndex("coords_x")));
			unUpLoad.setY(cursor.getString(cursor.getColumnIndex("coords_y")));
			list.add(unUpLoad);
		}
		cursor.close();
		db.close();
		upLoadData(list);
	}

	public void upLoadData(List<UnUpLoad> list) {
		String url = APIConstants.upload_api;
		AsyncHttpClient client = new AsyncHttpClient();
		client.setTimeout(1000 * 5);
		for (final UnUpLoad u : list) {
			RequestParams params = new RequestParams();
			params.put("BZ", u.getBZ());
			params.put("CJR", u.getCJR());
			params.put("CJSJ", u.getCJSJ());
			params.put("X", u.getX());
			params.put("Y", u.getY());
			params.put("QYMC", u.getQYMC());
			Log.d("tag", "upload:" + url + "   " + params.toString());
			client.post(url, params, new AsyncHttpResponseHandler() {

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					// TODO Auto-generated method stub
					super.onFailure(arg0, arg1, arg2, arg3);
					Log.d("tag", "后台上传失败：" + arg3.getMessage());
					Toast.makeText(context, "服务器异常，上传失败！", Toast.LENGTH_SHORT)
							.show();
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// TODO Auto-generated method stub
					super.onSuccess(arg0, arg1, arg2);
					Log.d("tag", "后台上传成功：" + u.getQYMC());
					String b_name = u.getQYMC();
					JSONObject json = null;
					try {
						json = new JSONObject(new String(arg2));
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if ("0".equals(json.opt("flag"))) {
						Toast.makeText(context, "数据上传成功：" + b_name,
								Toast.LENGTH_SHORT).show();
						FileUtils.makeDirs(b_name);
					} else if ("1".equals(json.opt("flag"))) {
						Toast.makeText(context, "此条数据上传重复。" + b_name,
								Toast.LENGTH_SHORT).show();
					}

					SQLiteDatabase db = dbHelper.getWritableDatabase();
					db.delete("unupload", "business_name=?",
							new String[] { b_name });
					db.close();
					count++;
				}

			});
		}
		flag = false;
		if (count > 0) {
			new AlertDialog.Builder(context).setTitle("后台数据")
					.setMessage("成功上传后台数据" + count + "条")
					.setPositiveButton("确定", null).show();
			count = 0;
		}
	}
}
